package com.magicalcoder.youyamvc.web.controller.admin.rolemodulepriority;

import com.magicalcoder.youyamvc.app.model.LogAdminOperate;
import com.magicalcoder.youyamvc.app.logadminoperate.service.LogAdminOperateProxyService;
import com.magicalcoder.youyamvc.app.logadminoperate.service.LogAdminOperateService;
import com.magicalcoder.youyamvc.app.model.defined.IntegerDate;
import com.magicalcoder.youyamvc.app.model.defined.IntegerObject;
import com.magicalcoder.youyamvc.app.rolemodulepriority.service.RoleModulePriorityService;
import com.magicalcoder.youyamvc.app.rolemodulepriority.service.RoleModulePriorityProxyService;
import com.magicalcoder.youyamvc.app.rolemodulepriority.constant.RoleModulePriorityConstant;
import com.magicalcoder.youyamvc.app.rolemodulepriority.util.RoleModulePriorityUtil;
import com.magicalcoder.youyamvc.app.rolemodulepriority.dto.RoleModulePriorityDto;
import com.magicalcoder.youyamvc.app.model.RoleModulePriority;
import com.magicalcoder.youyamvc.app.model.Priority;
import com.magicalcoder.youyamvc.core.common.utils.POIUtil;
import com.magicalcoder.youyamvc.core.common.utils.ProjectUtil;
import com.magicalcoder.youyamvc.core.common.utils.ReflectUtil;
import com.magicalcoder.youyamvc.core.common.utils.ListUtils;
import com.magicalcoder.youyamvc.core.common.utils.StringUtils;
import com.magicalcoder.youyamvc.core.common.dto.AjaxData;
import com.magicalcoder.youyamvc.core.common.utils.copy.Copyer;
import com.magicalcoder.youyamvc.core.spring.admin.AdminLoginController;
import com.magicalcoder.youyamvc.core.common.dto.InputSelectShowDto;
import com.magicalcoder.youyamvc.app.adminuser.util.AdminUserContextUtil;
import com.magicalcoder.youyamvc.app.model.Role;
import com.magicalcoder.youyamvc.app.role.service.RoleService;
import com.magicalcoder.youyamvc.app.model.Module;
import com.magicalcoder.youyamvc.app.module.service.ModuleService;
import com.magicalcoder.youyamvc.app.model.Priority;
import com.magicalcoder.youyamvc.app.priority.service.PriorityService;
import java.io.File;
import java.io.IOException;
import com.alibaba.fastjson.JSON;
import com.magicalcoder.youyamvc.core.common.file.FileHelper;
import com.magicalcoder.youyamvc.core.common.utils.copy.Copyer;
import com.magicalcoder.youyamvc.core.common.utils.serialize.SerializerFastJsonUtil;
import com.magicalcoder.youyamvc.core.spring.admin.AdminLoginController;
import org.springframework.web.multipart.MultipartFile;
import com.magicalcoder.youyamvc.core.common.exception.BusinessException;

import org.springframework.format.annotation.DateTimeFormat;
import java.util.*;
import java.math.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMethod;

/**
* 代码为自动生成 Created by www.magicalcoder.com
* 如果你改变了此类 read 请将此行删除
* 欢迎加入官方QQ群:323237052
*/

@RequestMapping({"/admin/role_module_priority"})
@Controller
public class AdminRoleModulePriorityListController extends AdminLoginController
{
    private final String moduleName = "role_module_priority";
    private final String allSqlFieldStr = ",id,role_id,module_id,priority_id,";
    @Resource
    private RoleService roleService;
    @Resource
    private ModuleService moduleService;
    @Resource
    private PriorityService priorityService;


    @Resource
    private LogAdminOperateProxyService logAdminOperateProxyService;
    @Resource
    private LogAdminOperateService logAdminOperateService;
    @Resource
    private RoleModulePriorityService roleModulePriorityService;
    @Resource
    private RoleModulePriorityProxyService roleModulePriorityProxyService;
    //列表页
    @RequestMapping(value={"list"}, method={RequestMethod.GET})
    public String list(ModelMap model,
        @RequestParam(required = false)Long roleId,
        @RequestParam(required = false)Long moduleId,
        @RequestParam(required = false)Long priorityId,
        @RequestParam(required = false) String queryParamCacheKey,
        @RequestParam(required = false) String focusTrId,
        HttpServletRequest request, HttpServletResponse response)
    {
        Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
        if(adminQueryPriority==null || !adminQueryPriority.getCanQuery()){
            return "admin/priorityAlert";
        }
        RoleModulePriority roleModulePriority = new RoleModulePriority();
                roleModulePriority.setRoleId(roleId);
                roleModulePriority.setModuleId(moduleId);
                roleModulePriority.setPriorityId(priorityId);
        model.addAttribute("queryParamCacheKey",queryParamCacheKey);
        model.addAttribute("focusTrId",focusTrId);
        model.addAttribute("adminPriority",adminQueryPriority);
        return "admin/rolemodulepriority/roleModulePriorityList";
    }

    //分页查询
    @RequestMapping(value={"page/{pageIndex}/{pageSize}/{pageCount}"}, method={RequestMethod.GET})
    public void page(@PathVariable Integer pageIndex,@PathVariable Integer pageSize, @PathVariable Integer pageCount,
        @RequestParam(required=false, value="orderBySqlField") String orderBySqlField,
        @RequestParam(required=false, value="descAsc") String descAsc,
        @RequestParam(required = false,value ="roleIdFirst")                            String roleIdFirst ,
        @RequestParam(required = false,value ="moduleIdFirst")                            String moduleIdFirst ,
        @RequestParam(required = false,value ="priorityIdFirst")                            String priorityIdFirst ,
        HttpServletRequest request, HttpServletResponse response)
    {
        try{
            Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
            if(adminQueryPriority==null || !adminQueryPriority.getCanQuery()){
                toWebFailureJson(response,"权限不足");
                return;
            }
            String orderBy = orderBySqlField +" "+ descAsc ;
            if(orderBySqlField==null || StringUtils.isBlank(orderBy)){
                    orderBy = "";
            }
            pageSize = Math.min(RoleModulePriorityConstant.PAGE_MAX_SIZE,pageSize);
            int idx = (pageIndex.intValue() - 1) * pageSize;

            Map<String,Object> query = ProjectUtil.buildMap("safeOrderBy", orderBy, new Object[] {
                    "roleIdFirst",ProjectUtil.toList(roleIdFirst ,Long.class),
                    "moduleIdFirst",ProjectUtil.toList(moduleIdFirst ,Long.class),
                    "priorityIdFirst",ProjectUtil.toList(priorityIdFirst ,Long.class),
            "start",idx,"limit", pageSize });

        boolean useRelateQuery = false;
            List pageList;
            pageList = this.roleModulePriorityService.getRoleModulePriorityList(query);
            query.remove("safeOrderBy");
            query.remove("start");
            query.remove("limit");
            if (pageCount == null || pageCount.intValue() == 0) {
                    pageCount = this.roleModulePriorityService.getRoleModulePriorityListCount(query);
            }

            Map ajaxData = new HashMap();
            ajaxData.put("pageList", dealSpecialField(pageList));
            ajaxData.put("pageCount", pageCount);
            toWebSuccessJson(response, ajaxData);
        }catch (Exception e){
            toWebExceptionJson(response,ProjectUtil.buildExceptionMsg(e.getMessage()));
        }
    }

    //处理特殊字段
    private List<Map<String,Object>> dealSpecialField(List<RoleModulePriority> pageList){
        List<Map<String,Object>> newPageList = new ArrayList<Map<String, Object>>(pageList.size());
        if(ListUtils.isNotBlank(pageList)){
            for(RoleModulePriority item:pageList){
                String json = JSON.toJSONString(item);
                Map<String,Object> obj = (Map<String,Object>)JSON.parse(json);
                newPageList.add(obj);
            }
        }
        return newPageList;
    }
    //根据自定义查询条件到编辑
    @RequestMapping({"/detail_param"})
    public String detailId(HttpServletRequest request,ModelMap model) {
        Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
        if(adminQueryPriority==null || !adminQueryPriority.getCanQuery()){
            return "admin/priorityAlert";
        }
        model.addAttribute("adminPriority",adminQueryPriority);
        Map<String,Object> reqMap = ProjectUtil.getParams(request);
        RoleModulePriority entity = this.roleModulePriorityService.selectOneRoleModulePriorityWillThrowException(reqMap);
        model.addAttribute("roleModulePriority", entity);
        foreignModel(entity,model);

        return "admin/rolemodulepriority/roleModulePriorityDetail";
    }
    //新增
    @RequestMapping({"/detail"})
    public String detail( HttpServletRequest request,
            @RequestParam(required = false)Long roleId,
            @RequestParam(required = false)Long moduleId,
            @RequestParam(required = false)Long priorityId,
        ModelMap model) {
        Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
        if(adminQueryPriority==null || !adminQueryPriority.getCanInsert()){
            return "admin/priorityAlert";
        }
        RoleModulePriority roleModulePriority = new RoleModulePriority();
                roleModulePriority.setRoleId(roleId);
                roleModulePriority.setModuleId(moduleId);
                roleModulePriority.setPriorityId(priorityId);
        foreignModel(roleModulePriority,model);
        model.addAttribute("roleModulePriority", roleModulePriority);
        model.addAttribute("adminPriority",adminQueryPriority);
        return "admin/rolemodulepriority/roleModulePriorityDetail";
    }

    private void foreignModel(RoleModulePriority entity,ModelMap model){
        Map<String,Object> map;
    }


    //根据主键到编辑
    @RequestMapping({"/detail/{id}"})
        public String detailId(@PathVariable Long id,
            @RequestParam(required = false) String queryParamCacheKey,
            @RequestParam(required = false) Long logAdminOperateId,
            HttpServletRequest request,ModelMap model) {
        Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
        if(adminQueryPriority==null || !adminQueryPriority.getCanQuery()){
            return "admin/priorityAlert";
        }
        RoleModulePriority entity = null;
        if(logAdminOperateId==null){
            entity = this.roleModulePriorityService.getRoleModulePriority(id);
        }else{
            LogAdminOperate logAdminOperate = logAdminOperateService.getLogAdminOperate(logAdminOperateId);
            if(logAdminOperate!=null){
                String formBody = logAdminOperate.getFormBody();
                entity = JSON.parseObject(formBody,RoleModulePriority.class);
            }
        }
        model.addAttribute("roleModulePriority", entity);
        model.addAttribute("queryParamCacheKey", queryParamCacheKey);
        foreignModel(entity,model);
        model.addAttribute("adminPriority",adminQueryPriority);
        model.addAttribute("logAdminOperateId",logAdminOperateId);
        model.addAttribute("logAdminOperateList",logAdminOperateProxyService.getSimpleList("role_module_priority",String.valueOf(id)));
        return "admin/rolemodulepriority/roleModulePriorityDetail";
    }

    //ajax更新状态
    @RequestMapping(value="ajax_update", method={RequestMethod.POST})
    public void ajaxUpdate(@ModelAttribute RoleModulePriority roleModulePriority,
        HttpServletRequest request,HttpServletResponse response,ModelMap model) {
        Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
        if(adminQueryPriority==null || !adminQueryPriority.getCanUpdate()){
            toWebFailureJson(response,"权限不足");
            return;
        }
        try{
            this.roleModulePriorityService.updateRoleModulePriorityWithoutNull(roleModulePriority);
            toWebSuccessJson(response);
        }catch (Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            model.addAttribute("exceptionMsg",exceptionMsg);
            toWebFailureJson(response,exceptionMsg);
        }
    }
    //保存
    @RequestMapping(value="save", method={RequestMethod.POST})
    public String save(@ModelAttribute RoleModulePriority roleModulePriority,
        @RequestParam(required = false) String queryParamCacheKey,
        HttpServletRequest request,ModelMap model) {
        try{
            model.addAttribute("roleModulePriority",roleModulePriority);
            foreignModel(roleModulePriority,model);
            Date now = new Date();
            if (roleModulePriority.getId() == null) {
                Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
                if(adminQueryPriority==null || !adminQueryPriority.getCanInsert()){
                    return "admin/priorityAlert";
                }
                this.roleModulePriorityService.insertRoleModulePriority(roleModulePriority);
                logAdminOperateProxyService.insertIntoLog(request,"insert",String.valueOf(roleModulePriority.getId()),roleModulePriority);
            } else {
                Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
                if(adminQueryPriority==null || !adminQueryPriority.getCanUpdate()){
                    return "admin/priorityAlert";
                }
                RoleModulePriority entity = this.roleModulePriorityService.getRoleModulePriority(roleModulePriority.getId());
                if(entity==null){
                    this.roleModulePriorityService.replaceRoleModulePriority(roleModulePriority);
                    logAdminOperateProxyService.insertIntoLog(request,"insert",String.valueOf(roleModulePriority.getId()),roleModulePriority);
                }else{
                    Copyer.copy(roleModulePriority, entity);
                    this.roleModulePriorityService.updateRoleModulePriority(entity);
                    logAdminOperateProxyService.insertIntoLog(request,"update",String.valueOf(roleModulePriority.getId()),entity);
                }
                            }
        }catch (Exception e){
            model.addAttribute("queryParamCacheKey", queryParamCacheKey);
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            model.addAttribute("exceptionMsg",exceptionMsg);
            return "admin/rolemodulepriority/roleModulePriorityDetail";
        }
        return "redirect:/admin/role_module_priority/list?queryParamCacheKey="+queryParamCacheKey+"&focusTrId="+roleModulePriority.getId();
    }

    //ajax保存
    @RequestMapping(value="ajax_save", method={RequestMethod.POST})
    public void save(@ModelAttribute RoleModulePriority roleModulePriority,
        HttpServletRequest request,HttpServletResponse response,ModelMap model) {
        Long id = roleModulePriority.getId();
        try{
            foreignModel(roleModulePriority,model);
            Date now = new Date();
            if (roleModulePriority.getId() == null) {
                Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
                if(adminQueryPriority==null || !adminQueryPriority.getCanInsert()){
                    toWebFailureJson(response,"角色模块权限无插入数据权限");
                    return;
                }
                id = this.roleModulePriorityService.insertRoleModulePriority(roleModulePriority);
                logAdminOperateProxyService.insertIntoLog(request,"insert",String.valueOf(roleModulePriority.getId()),roleModulePriority);
            } else {
                Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
                if(adminQueryPriority==null || !adminQueryPriority.getCanUpdate()){
                    toWebFailureJson(response,"角色模块权限无更新数据权限");
                    return;
                }
                RoleModulePriority entity = this.roleModulePriorityService.getRoleModulePriority(roleModulePriority.getId());
                Copyer.copy(roleModulePriority, entity);
                this.roleModulePriorityService.updateRoleModulePriority(entity);
                logAdminOperateProxyService.insertIntoLog(request,"update",String.valueOf(roleModulePriority.getId()),entity);
            }
        }catch (Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(response,exceptionMsg);
            return;
        }
        toWebSuccessJson(response,id,false);
    }

    //ajax批量保存
    @RequestMapping(value="batch_save", method={RequestMethod.POST})
    public void save(@RequestParam String saveJson,
     @RequestParam(required = false) Long roleId,
     @RequestParam(required = false) Long moduleId,
     @RequestParam(required = false) Long priorityId,
        HttpServletResponse response,HttpServletRequest request,ModelMap model) {
        try{
            List<RoleModulePriority> roleModulePriorityList = SerializerFastJsonUtil.get().readJsonList(saveJson,RoleModulePriority.class);
            List<RoleModulePriority> insert = new ArrayList<RoleModulePriority>();
            List<RoleModulePriority> update = new ArrayList<RoleModulePriority>();
            for(RoleModulePriority roleModulePriority:roleModulePriorityList){
                if(roleModulePriority.getRoleId() == null){
                    roleModulePriority.setRoleId( roleId);
                }
                if(roleModulePriority.getModuleId() == null){
                    roleModulePriority.setModuleId( moduleId);
                }
                if(roleModulePriority.getPriorityId() == null){
                    roleModulePriority.setPriorityId( priorityId);
                }

                if(roleModulePriority.getId()==null){
                    insert.add(roleModulePriority);
                }else {
                    update.add(roleModulePriority);
                }
            }
            Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
            String priority = "";
            if(ListUtils.isNotBlank(insert)){
                if(adminQueryPriority==null || !adminQueryPriority.getCanInsert()){
                    priority = "角色模块权限无插入数据权限";
                }else {
                    roleModulePriorityService.batchInsertRoleModulePriority(insert);
                    logAdminOperateProxyService.insertIntoLog(request,"batch_insert",null,insert);
                }
            }
            if(ListUtils.isNotBlank(update)){
                if(adminQueryPriority==null || !adminQueryPriority.getCanUpdate()){
                    priority += "角色模块权限无更新数据权限";
                }else {
                    roleModulePriorityService.batchUpdateRoleModulePriority(update);
                    logAdminOperateProxyService.insertIntoLog(request,"batch_update",null,update);
                }
            }

            if(StringUtils.isBlank(priority)){
                toWebSuccessJson(response);
            }else {
                toWebFailureJson(response,priority);
            }
        }catch(Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(response,exceptionMsg);
        }
    }

    //删除
    @RequestMapping({"/delete/{id}"})
    public void delete(@PathVariable Long id,
        HttpServletRequest request, HttpServletResponse response) {
        try{
            Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
            if(adminQueryPriority==null || !adminQueryPriority.getCanDelete()){
                toWebFailureJson(response,"权限不足");
                return;
            }
            this.roleModulePriorityService.deleteRoleModulePriority(id);
            toWebSuccessJson(response);
            logAdminOperateProxyService.insertIntoLog(request,"delete",String.valueOf(id),null);
        }catch(Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(response,exceptionMsg);
        }
    }
    //批量删除
    @RequestMapping({"/batchdelete/{ids}"})
    public void batchDelete(@PathVariable String ids, HttpServletRequest request,HttpServletResponse response) {
        try{
            Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
            if(adminQueryPriority==null || !adminQueryPriority.getCanDelete()){
                toWebFailureJson(response,"权限不足");
                return;
            }
            if(StringUtils.isNotBlank(ids)){
                String[] idArr = ids.split(",");
                List<Long> list = new ArrayList<Long>();
                for(String id:idArr){
                    if(StringUtils.isNotBlank(id)){
                        list.add(Long.valueOf(id));
                    }
                }
                if(ListUtils.isNotBlank(list)){
                    this.roleModulePriorityService.batchDeleteRoleModulePriority(list);
                    toWebSuccessJson(response);
                    logAdminOperateProxyService.insertIntoLog(request,"batch_delete",ids,null);
                }
            }else{
                toWebFailureJson(response,"没有要删除的主键");
            }
        }catch(Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(response,exceptionMsg);
        }
    }

    //批量复制
    @RequestMapping({"/batch_copy/{ids}"})
    public void batchCopy(@PathVariable String ids, HttpServletRequest request,HttpServletResponse response) {
        try{
            Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
            if(adminQueryPriority==null || !adminQueryPriority.getCanInsert()){
                toWebFailureJson(response,"新增权限不足");
                return;
            }
            if(StringUtils.isNotBlank(ids)){
                String[] idArr = ids.split(",");
                List<Long> list = new ArrayList<Long>();
                for(String id:idArr){
                    if(StringUtils.isNotBlank(id)){
                        list.add(Long.valueOf(id));
                    }
                }
                if(ListUtils.isNotBlank(list)){
                    for(Long id:list){
                        RoleModulePriority entity = roleModulePriorityService.getRoleModulePriority(id);
                        entity.setId(null);
                        roleModulePriorityService.insertRoleModulePriority(entity);
                        logAdminOperateProxyService.insertIntoLog(request,"insert",String.valueOf(entity.getId()),entity);
                    }
                }
                toWebSuccessJson(response);
            }
            else{
                toWebFailureJson(response,"没有要删除的主键");
            }
        }catch(Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(response,exceptionMsg);
        }
    }


    /**
    * 列表页批量更新
    */
    @RequestMapping(value="batch_update/{ids}", method={RequestMethod.POST})
    public void batchUpdate(@PathVariable String ids,@ModelAttribute RoleModulePriority entity,
    HttpServletRequest request,HttpServletResponse response,ModelMap model) {

        try{
            if(StringUtils.isNotBlank(ids)){
                String[] idArr = ids.split(",");
                List<Long> list = new ArrayList<Long>();
                for(String id:idArr){
                    if(StringUtils.isNotBlank(id)){
                        list.add(Long.valueOf(id));
                    }
                }
                if(ListUtils.isNotBlank(list)){
                    for(Long id:list){
                        entity.setId(id);
                        roleModulePriorityService.updateRoleModulePriorityWithoutNull(entity);
                        logAdminOperateProxyService.insertIntoLog(request,"update",String.valueOf(entity.getId()),entity);
                    }
                }
                toWebSuccessJson(response);
            }
            else{
                toWebFailureJson(response,"没有要更新的主键");
            }
        }catch(Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(response,exceptionMsg);
        }
    }
    //清空表结构
    @RequestMapping(value = "truncate")
    public void truncate(HttpServletRequest request,HttpServletResponse response) {
        Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
        if(adminQueryPriority==null || !adminQueryPriority.getCanTruncate()){
            toWebFailureJson(response,"权限不足");
            return;
        }
        this.roleModulePriorityService.truncateRoleModulePriority();
        toWebSuccessJson(response);
        logAdminOperateProxyService.insertIntoLog(request,"truncate",null,null);
    }
    //文件导入数据
    @RequestMapping(value = "import")
    public void importJson(@RequestParam MultipartFile myfiles,HttpServletRequest request,HttpServletResponse response) throws IOException {
        Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
        if(adminQueryPriority==null || !adminQueryPriority.getCanImport()){
            toWebFailureJson(response,"权限不足");
            return;
        }
        try{
            if(myfiles.getOriginalFilename().endsWith(".json")){
                String fileContent = FileHelper.fastReadFileUTF8(myfiles.getInputStream());
                List<RoleModulePriority> list = SerializerFastJsonUtil.get().readJsonList(fileContent,RoleModulePriority.class);
                if(ListUtils.isNotBlank(list)){
                    this.roleModulePriorityService.transactionImportJsonList(list);
                }
                toWebSuccessJson(response);
                logAdminOperateProxyService.insertIntoLog(request,"import_json",null,list);
            }else if(myfiles.getOriginalFilename().endsWith(".xlsx")){
                POIUtil<RoleModulePriority> poiUtil = new POIUtil<RoleModulePriority>();
                List<RoleModulePriority> list = poiUtil.readExcel(myfiles.getInputStream(),RoleModulePriority.class);
                if(ListUtils.isNotBlank(list)){
                    this.roleModulePriorityService.transactionImportJsonList(list);
                }
                toWebSuccessJson(response);
                logAdminOperateProxyService.insertIntoLog(request,"import_excel",null,list);
            }else {
                toWebFailureJson(response, "不支持的文件后缀");
            }
        }catch(Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(response,exceptionMsg);
        }
    }
    //json文件导出
    @RequestMapping(value = "export/{exportFile}/{start}/{limit}",method = RequestMethod.GET)
    public void exportJson(@PathVariable String exportFile,@PathVariable Integer start,@PathVariable Integer limit,
        @RequestParam(required=false, value="orderBySqlField") String orderBySqlField,
        @RequestParam(required=false, value="descAsc") String descAsc,
        @RequestParam(required = false,value ="roleIdFirst")                            String roleIdFirst ,
        @RequestParam(required = false,value ="moduleIdFirst")                            String moduleIdFirst ,
        @RequestParam(required = false,value ="priorityIdFirst")                            String priorityIdFirst ,
        HttpServletRequest request,HttpServletResponse response){
        try{
            Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
            if(adminQueryPriority==null || !adminQueryPriority.getCanExport()){
                toWebFailureJson(response,"权限不足");
                return;
            }
            String orderBy = orderBySqlField +" "+ descAsc ;
            if(orderBySqlField==null || StringUtils.isBlank(orderBy)){
                orderBy = "";
            }
            Map<String,Object> query = ProjectUtil.buildMap("safeOrderBy", orderBy, new Object[] {
                    "roleIdFirst",ProjectUtil.toList(roleIdFirst ,Long.class),
                    "moduleIdFirst",ProjectUtil.toList(moduleIdFirst ,Long.class),
                    "priorityIdFirst",ProjectUtil.toList(priorityIdFirst ,Long.class),
            "start",start,"limit", limit });

        boolean useRelateQuery = false;
            List pageList;
                pageList = this.roleModulePriorityService.getRoleModulePriorityList(query);

            String file = moduleName;
            File tmpFile = null;
            try {
                if("excel".equals(exportFile)){
                    tmpFile = File.createTempFile(file,".xlsx");
                    POIUtil<RoleModulePriority> poiUtil = new POIUtil<RoleModulePriority>();
                    poiUtil.writeExcelToTempFile(pageList
                        ,new String[]{ "主键(bigint)", "角色(bigint)", "模块(bigint)", "权限(bigint)"}
                        ,new String[]{ "", "", "", ""}
                        ,tmpFile);
                }else {
                    tmpFile = File.createTempFile(file,".json");
                    String json = JSON.toJSONString(pageList, true);
                    FileHelper.fastWriteFileUTF8(tmpFile, json);
                }
                toFile(response, tmpFile);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if(tmpFile!=null){
                    tmpFile.delete();
                }
            }
        }catch (Exception e){
            toWebExceptionJson(response,ProjectUtil.buildExceptionMsg(e.getMessage()));
        }
    }


//===================搜索下拉框 外键查询使用begin=================================
    @RequestMapping(value = "type_ahead_search",method = RequestMethod.GET)
    public void typeAheadSearch(@RequestParam(value = "keyword",required = false) String keyword,
        @RequestParam(value = "foreignJavaField",required = false) String foreignJavaField,
        @RequestParam(value = "selectValue",required = false) String selectValue,
        HttpServletResponse response){
        try{
            if(StringUtils.isBlank(selectValue)){
                selectValue = selectValue();
            }
            List<RoleModulePriority> list = roleModulePriorityService.tryQueryList(keyword,selectValue,foreignJavaField);
            toSimpleJson(response,ProjectUtil.showSelect2List(list,selectValue,foreignJavaField));
        }catch (Exception e){
            toWebExceptionJson(response,ProjectUtil.buildExceptionMsg(e.getMessage()));
        }
    }

    private String selectValue(){
        StringBuffer sb = new StringBuffer();
        return StringUtils.deleteLastChar(sb.toString());
    }

    //searchMapListJson [{"字段名":字段值},{"字段名":字段值}]
    @RequestMapping(value = "batch_search_type_ahead",method = RequestMethod.GET)
    public void batchSearchForTypeAhead(@RequestParam String searchMapListJson,
                                        @RequestParam String foreignJavaField,
                                    HttpServletResponse response){
        try{
            List<Map<String,Object>> list = (List<Map<String,Object>>)JSON.parse(searchMapListJson);
            List<RoleModulePriority> returnList = new ArrayList<RoleModulePriority>();
            if(ListUtils.isNotBlank(list)){
                Map<String,Boolean> existMap = new HashMap<String,Boolean>();
                for(Map<String,Object> mapDto:list){
                    Set<String> keys = mapDto.keySet();
                    String key = null;
                    Object value = null;
                    for(String k:keys){
                        key = k;
                        value = mapDto.get(k);
                    }
                    if(key!=null && value!=null){
                        if(!existMap.containsKey(value+"")){//不要重复查询
                            existMap.put(value+"",true);
                            List<RoleModulePriority> entityList = roleModulePriorityService.getRoleModulePriorityList(ProjectUtil.buildMap(key,value));
                            if(ListUtils.isNotBlank(entityList)){
                                returnList.addAll(entityList);
                            }
                        }
                    }
                }
            }
            Map<String,RoleModulePriority> returnMap = new HashMap<String,RoleModulePriority>();
            if(ListUtils.isNotBlank(returnList)){
                ReflectUtil reflectUtil = new ReflectUtil();
                for(RoleModulePriority entity:returnList){
                    returnMap.put(reflectUtil.getBeanValue(entity,foreignJavaField)+"",entity);
                }
            }
            toWebSuccessJson(response,ProjectUtil.buildMap("foreignTableName","role_module_priority","selectValue",selectValue(),"returnMap",returnMap));
        }catch (Exception e){
            toWebExceptionJson(response,ProjectUtil.buildExceptionMsg(e.getMessage()));
        }
    }
    //===================搜索下拉框 外键查询使用end======================================//

    //===================统计begin=================================//
    @RequestMapping(value = "group_date_count_statistics/{start}/{limit}")
    public void groupDateCountStatistics(@PathVariable Integer start,@PathVariable Integer limit,
                           @RequestParam String groupDateCountBySqlField,
                           @RequestParam Integer groupDateCountByPrecision,
        @RequestParam(required = false,value ="roleIdFirst")                            String roleIdFirst ,
        @RequestParam(required = false,value ="moduleIdFirst")                            String moduleIdFirst ,
        @RequestParam(required = false,value ="priorityIdFirst")                            String priorityIdFirst ,
                           HttpServletRequest request, HttpServletResponse response){
        try{
            Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
            if(adminQueryPriority==null || !adminQueryPriority.getCanStatistics()){
                toWebFailureJson(response,"权限不足");
                return;
            }
            if(!ProjectUtil.sqlFieldValid(allSqlFieldStr,groupDateCountBySqlField)){
                toWebFailureJson(response,"sql注入无效");
                return;
            }

            Map<String,Object> query = ProjectUtil.buildMap(
                    "roleIdFirst",ProjectUtil.toList(roleIdFirst ,Long.class),
                    "moduleIdFirst",ProjectUtil.toList(moduleIdFirst ,Long.class),
                    "priorityIdFirst",ProjectUtil.toList(priorityIdFirst ,Long.class),
                    "groupDateCountBySqlField",groupDateCountBySqlField ,
                    "groupBy",ProjectUtil.statisticsDateCountGroupBy(groupDateCountBySqlField,groupDateCountByPrecision),
                    "start",start,"limit", limit);
            List<IntegerDate> pageList = this.roleModulePriorityService.statisticsDateCountList(query);
            toWebSuccessJson(response, pageList);
        }catch (Exception e){
            toWebExceptionJson(response,ProjectUtil.buildExceptionMsg(e.getMessage()));
        }
    }
    @RequestMapping(value = "group_date_interval_statistics/{start}/{limit}")
    public void groupDateIntervalStatistics(@PathVariable Integer start,@PathVariable Integer limit,
                           @RequestParam String groupDateIntervalBySqlField,
        @RequestParam(required = false,value ="roleIdFirst")                            String roleIdFirst ,
        @RequestParam(required = false,value ="moduleIdFirst")                            String moduleIdFirst ,
        @RequestParam(required = false,value ="priorityIdFirst")                            String priorityIdFirst ,
                           HttpServletRequest request, HttpServletResponse response){
        try{
            Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
            if(adminQueryPriority==null || !adminQueryPriority.getCanStatistics()){
                toWebFailureJson(response,"权限不足");
                return;
            }
            if(!ProjectUtil.sqlFieldValid(allSqlFieldStr,groupDateIntervalBySqlField)){
                toWebFailureJson(response,"sql注入无效");
                return;
            }
            String orderBy = groupDateIntervalBySqlField+" asc";
            Map<String,Object> query = ProjectUtil.buildMap("safeOrderBy", orderBy, new Object[] {
                    "roleIdFirst",ProjectUtil.toList(roleIdFirst ,Long.class),
                    "moduleIdFirst",ProjectUtil.toList(moduleIdFirst ,Long.class),
                    "priorityIdFirst",ProjectUtil.toList(priorityIdFirst ,Long.class),
                    "safeGroupBy",groupDateIntervalBySqlField ,
                    "start",start,"limit", limit });
            List<IntegerDate> pageList = this.roleModulePriorityService.statisticsDateIntervalList(query);
            toWebSuccessJson(response, pageList);
        }catch (Exception e){
            toWebExceptionJson(response,ProjectUtil.buildExceptionMsg(e.getMessage()));
        }
    }
    @RequestMapping(value = "group_statistics/{start}/{limit}")
    public void groupStatistics(@PathVariable Integer start,@PathVariable Integer limit,
                           @RequestParam String groupBySqlField,
        @RequestParam(required = false,value ="roleIdFirst")                            String roleIdFirst ,
        @RequestParam(required = false,value ="moduleIdFirst")                            String moduleIdFirst ,
        @RequestParam(required = false,value ="priorityIdFirst")                            String priorityIdFirst ,
                            HttpServletRequest request, HttpServletResponse response){
        try{
            Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
            if(adminQueryPriority==null || !adminQueryPriority.getCanStatistics()){
                toWebFailureJson(response,"权限不足");
                return;
            }
            Map<String,Object> query = ProjectUtil.buildMap("orderBy", "total desc", new Object[] {
                    "roleIdFirst",ProjectUtil.toList(roleIdFirst ,Long.class),
                    "moduleIdFirst",ProjectUtil.toList(moduleIdFirst ,Long.class),
                    "priorityIdFirst",ProjectUtil.toList(priorityIdFirst ,Long.class),
                    "safeGroupBy",groupBySqlField,
                    "start",start,"limit", limit });
            List<IntegerObject> pageList = this.roleModulePriorityService.statisticsGroupList(query);
            toWebSuccessJson(response, pageList);
        }catch (Exception e){
            toWebExceptionJson(response,ProjectUtil.buildExceptionMsg(e.getMessage()));
        }
    }
    //===================统计end===================================//
}
